<?php
/**
 * 封装 DsCache, 单件模式 更易操作;
 * @filesource _cache.class.php
 * @package peck
 * @subpackage _cache
 * @version $id: 2.0, utf8, Sat Dec  5 14:10:38 CST 2009
 * @author LD King <kldscs[at]gmail.com>
 * @copyright Copyleft (D.) 2007 - 2009 MiFunny China Inc.
 * @link http://mifunny.info/
 * @example
 *   
 *   //文件缓存
 *   $GLOBALS['__configs']['cache']['phpfile'] = array(
 *   	'cache_dir' => '/tmp', //缓存目录(必须)
 *   	'life_time' => 900, //全局缓存时间 900s.
 *   	);
 *   
 *   //内存缓存
 *   $GLOBALS['__configs']['cache']['memcache'] = array(
 *      'disable' => false,
 *   	'type' => 'phpmencached' //缓存类型(必须)
 *   	'servers' => array(		//缓存服务器,至少填一个(必需)
 *   			array( 'host' => '127.0.0.1', 'port' => '11211', 'weight' => 99, ),
 *   			array( 'host' => '192.168.1.112', 'port' => '11211', 'weight' => 32, ),	
 *   			), 
 *   	'life_time' => 900, //全局缓存时间 900s.
 *   	'persistent' => true, //持久连接
 *   	'compressed' => false, //压缩数据与否
 *   	'encoding_key' => false, //加密缓存ID, 即 MD5($key)
 *   	);
 *   
 *   //约定: 如果 'life_time' 设置为 0 表示不检查缓存有效期(即缓存永久有效).
 *
 *	 $cache = _cache::object();
 *   $cache->set('select * from test', $data); //缓存变量
 *   $cache->get('cache id 1234'); //得到缓存
 *   $cache->remove('my cache file'); //清除特定缓存文件
 *   $cache->clean(); //清空缓存目录
 */
class _cache{
    //private static $instance;
    

    /**
     * 构造,析构函数
     */
    private function __construct(){}
    private function __clone(){}

    /**
     * 获得缓存静态对像
     */
    public static function object( $offset=null ){
        $dkey = empty($offset) ? 'default' : $offset;
        $key = 'cache:'.$dkey;
        $oo = '__objects';
        
        if( !empty($GLOBALS[$oo][$key]) ){
            return $GLOBALS[$oo][$key];
        }

        $cc =& $GLOBALS['__configs']['cache'];
		if ( empty($cc) ){
            throw new LogicException('('.__METHOD__.')Error: configure array should be give !');
            return false;
        }
        
        //判断配置数组
        if( empty($offset) || empty($cc[$dkey]) ){
            reset($cc);
            $policy = current($cc);
        }else{
            $policy = $cc[$dkey];       
        }

        $ctype = empty($policy['type']) ? 'phpfiled' : $policy['type'];
        $ctype = empty($policy['disable']) ? $ctype : 'dscache';
        $ctype = '_'.$ctype;
        $filesource =  dirname(__FILE__).DIRECTORY_SEPARATOR.$ctype.'.class.php';

        if( is_file($filesource) ){
            require_once $filesource; 
            $object = new $ctype($policy);
        }else{
            throw new LogicException('('.__METHOD__.')Error: Start Cache('.$ctype.') Failed !');
            return false;
        }

        $GLOBALS[$oo][$key] = $object;
        return $GLOBALS[$oo][$key];
    }
    
}//END class Cache

